package com.zml.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;


public class Splite {

    private static final int pageSize = 10;

    public static int partitionPdfFile(String filePathStr, String encrypt) throws IOException, DocumentException {
        int n;
        Path filePath = Paths.get(filePathStr);
        Document document = null;
        PdfCopy copy = null;
        int nums = 0;
        PdfReader reader = null;

        reader = new PdfReader(filePathStr);
        PdfReader.unethicalreading = true;
        nums = reader.getNumberOfPages();
        if (nums % pageSize != 0) {
            n = nums / pageSize + 1;
        } else {
            n = nums / pageSize;
        }


        String savepath = null;
        ArrayList<String> savepaths = new ArrayList<>();
        String fileOnlyName = PdfUtil.getOnlyName(filePathStr);
        String desFileDir = Paths.get(filePath.getParent().toString(), fileOnlyName).toString();
        File myPath = new File(desFileDir);
        if (!myPath.exists()) {
            myPath.mkdir();
        }
        for (int i = 0; i < n; i++) {
            savepath = Paths.get(desFileDir, i + "_" + filePath.getFileName()).toString();
            savepaths.add(savepath);
        }

        for (int i = 0; i < n; i++) {
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(savepaths.get(i)));
            document.open();
            copy.open();
            for (int j = pageSize * i + 1; j <= pageSize * (i + 1) && j <= nums; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }

            if (copy != null) {

                copy.close();
            }
            if (document != null) {

                document.close();
            }
            System.out.println("正在加密的文件分片：" + savepaths.get(i));
            EncryptPDF.EncryptPdf(savepaths.get(i), encrypt);
        }

        if (reader != null) {
            reader.close();
        }

        return nums;
    }


    public static void main(String[] args) throws IOException, DocumentException {
        String filePathStr = "E:\\Idea\\Java\\pdf-web\\PdfFiles\\24_Go语言编程.pdf";
        System.out.println(new File(filePathStr).exists());
    }


}
